package com.tuomaxu.core;

import com.tuomaxu.config.BoundSql;
import com.tuomaxu.config.Configuration;
import com.tuomaxu.config.MappedStatement;
import com.tuomaxu.utils.BoundSqlParser;
import com.tuomaxu.utils.ParameterMapping;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ExecutorImp implements Executor{
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        Connection connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = new BoundSqlParser().parser(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        String paramterType =  mappedStatement.getParamterType();
        Class paramterTypeClass = (paramterType!=null)?Class.forName(mappedStatement.getParamterType()):null;
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String field = parameterMapping.getContent();//sql中 #{field}
            //通过通过field和输入对象类型，访问这个对象的这个字段
            //如果是java.lang.Integer则直接使用,感觉不太对，但想不到其他的处理办法
            if("java.lang.Integer".equals(paramterType)){
                preparedStatement.setObject(i+1,params[0]);
            }else {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field, paramterTypeClass);
                Method readMethod = propertyDescriptor.getReadMethod();
                Object value = readMethod.invoke(params[0]);
                preparedStatement.setObject(i+1,value);
            }

        }

        ResultSet resultSet = preparedStatement.executeQuery();
        Class resultTypeClass = Class.forName(mappedStatement.getResultType());

        ArrayList<E> objects = new ArrayList<>();

        while (resultSet.next()){
            E o = (E) resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {

                // 字段名
                String columnName = metaData.getColumnName(i+1);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);

            }
            objects.add(o);

        }
        connection.close();
        return objects;
    }

    @Override
    public void execute(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        Connection connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = new BoundSqlParser().parser(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        String paramterType =  mappedStatement.getParamterType();
        Class paramterTypeClass = (paramterType!=null)?Class.forName(mappedStatement.getParamterType()):null;
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String field = parameterMapping.getContent();//sql中 #{field}
            //通过通过field和输入对象类型，访问这个对象的这个字段
            //如果是java.lang.Integer则直接使用,感觉不太对，但想不到其他的处理办法
            if("java.lang.Integer".equals(paramterType)){
                preparedStatement.setObject(i+1,params[0]);
            }else {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field, paramterTypeClass);
                Method readMethod = propertyDescriptor.getReadMethod();
                Object value = readMethod.invoke(params[0]);
                preparedStatement.setObject(i+1,value);
            }
        }
        preparedStatement.executeUpdate();
        connection.close();
    }


}
